﻿using System;
using System.Text;

namespace client;

public class NetPack
{
    public const int PACK_LEN_SIZE = 4;
    public const int PACK_PID_SIZE = 4;
    public const int PACK_HEAD_SIZE = 8;
    //数据包大小
    public int DataSize = 0;
    //协议号
    public uint Pid = 0;
    //数据内容
    public byte[] Data;

    private void EncodeBody(byte[] body)
    {
        int length = PACK_HEAD_SIZE;

        if (body != null)
            length += body.Length;

        int index = PACK_HEAD_SIZE;
        while (index < length)
        {
            Data[index] = body[index - PACK_HEAD_SIZE];
            index++;
        }
    }
    public void Encode(UInt16 pid)
    {
        Pid = pid;
        DataSize = 0;
        Data = new byte[PACK_HEAD_SIZE + DataSize];

        Data[0] = (byte)(DataSize & 0xff);
        Data[1] = (byte)((DataSize & 0xff00) >> 8);
        Data[2] = (byte)((DataSize & 0xff0000) >> 16);
        Data[3] = (byte)((DataSize & 0xff000000) >> 24);

        Data[4] = (byte)(pid & 0xff);
        Data[5] = (byte)((pid & 0xff00) >> 8);
    }
    public void Encode(UInt16 pid, byte[] body)
    {
        Pid = pid;
        DataSize = body.Length;
        Data = new byte[PACK_HEAD_SIZE + DataSize];

        EncodeBody(body);

        Data[0] = (byte)(DataSize & 0xff);
        Data[1] = (byte)((DataSize & 0xff00) >> 8);
        Data[2] = (byte)((DataSize & 0xff0000) >> 16);
        Data[3] = (byte)((DataSize & 0xff000000) >> 24);

        Data[4] = (byte)(pid & 0xff);
        Data[5] = (byte)((pid & 0xff00) >> 8);
    }
    //public static void Decode(byte[] buffer, out byte[] body, out int len)
    //{
    //    len = buffer.Length - PACK_HEAD_SIZE;
    //    body = new byte[len];
    //    int index = 0;
    //    while (index < buffer.Length)
    //    {
    //        body[index] = buffer[index + PACK_HEAD_SIZE];
    //        index++;
    //    }
    //}
}
